<template>

  <div id="screenshot-target">

    <!-- 这里放置你想要截屏的内容 -->
    <div class="common-layout" >
      <div  v-show="takePhoto">
        <el-dialog v-model="takePhoto" title="考试前先拍照比对人脸" width="50%" center :show-close="false" :close-on-click-modal="false"
                   :close-on-press-escape="false"
        >
          <!--阅读须知和开启摄像头-->
          <el-row justify="space-between">
            <el-col span="10">
              <div style="width: 100%;height: 100%">
                <el-card  shadow="always" style="width:100%;height:80%;font-weight: bold;word-wrap: break-word;">
                  <h1 style="text-align: center;font-weight: bold">注意事项</h1>
                  <p style="font-weight: bold;color: #7F7F7F">请打开摄像头，并点击拍照,比对人脸。</p>

                  <p style="color: #7F7F7F"> 编程题请先暂存保存你的代码，防止代码丢失</p>
                  <p style="color: #7F7F7F">考试时间结束后自动交卷，请控制时间</p>
                  <p style="color: #7F7F7F">请勿中途换电脑，违者作弊处置</p>
                  <p style="color: #7F7F7F">请勿中途切换页面，控制浏览器页面</p>
                  <p style="color: #7F7F7F">请点击下方打开摄像头按钮</p>
                  <el-icon  :size="40" style="display:block;margin: 0 auto;"><Bottom /></el-icon>
                </el-card>
                <el-button @click="getCompetence(),cameraFlag=true" style="margin-left: 30% ;margin-top: 2%;background-color: #5999FE;color: white">打开摄像头</el-button>
              </div>
            </el-col>
            <el-col span="2">
              <div style="background-color: #7F7F7F;width: 3%;height: 100%">&nbsp;</div>
            </el-col>
            <el-col span="12">
              <el-card  shadow="always" style="width:100%;height:80%;" id="face-photo">
                <!--<h1 style="text-align: center;font-weight: bold">点击拍照</h1>-->
                <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay ></video>
                <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>
                <div class="button"  style="height: 100px">

                  <!--<el-button @click="stopNavigator()">关闭摄像头</el-button>-->

                </div>
              </el-card>
              <el-button @click="openStartScreenshot('takePhoto')" style="margin-left: 45% ;margin-top: 2%;background-color: #5999FE;color: white">拍照</el-button>

            </el-col>
          </el-row>
        </el-dialog>
      </div>


      <el-container v-show="!takePhoto">
        <el-header style="height:30%">
          <!--题目类别选择-->
          <div style="height:30%;display: flex;  ">
            <!--拍照-->

            <!--答题卡-->
            <el-card class="dt" shadow="hover" style="margin-right: 2%;margin-top: 20px; margin-left: 30% /* 使得右边div靠右，左边留出空间 */  ">
              <!--考试倒计时-->
              <div>
                <span>考试倒计时: {{ remainingHours }}小时 {{ remainingMinutes }}分钟 {{ remainingSeconds }}秒</span>
              </div>
              <div class="line" style=" height: 1px;background-color: #409EFF;margin: 2px">
              </div>
              <!--  答题卡内容-->
              <div class="content">
                <span>答题卡</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                <span>未答题：</span>
                <div
                    style="display: inline-block;background-color: white;height: 20px;width: 20px;margin: 3px;border:1px solid#409EFF; ">
                  &nbsp;
                </div>
                &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                <span>已答题(不代表提交)：</span>
                <div style="display: inline-block;background-color: #409EFF;height: 20px;width: 20px;margin: 3px">&nbsp;
                </div>
                <div class="line" style=" height: 1px;background-color: #409EFF;margin: 2px"></div>
                <div>
                  <span>客观题</span>
                  <div class="line" style=" height: 1px;background-color: #409EFF;margin: 2px"></div>
                  <el-button class="questionItem" :type="item.answer==null?'':'primary'"
                             v-for="(item,index)  in ExamPaper.objectiveQuestions" size="small" :key="index"
                             @click="objDTK(index)"> {{ index + 1 }}
                  </el-button>
                </div>
                <div>
                  <span>编程题</span>
                  <div class="line" style=" height: 1px;background-color: #409EFF;margin: 2px"></div>
                  <el-button class="questionItem" :type="item.answer==null?'':'primary'"
                             v-for="(item,index)  in ExamPaper.programmingQuestions" size="small" :key="index"
                             @click="proDTK(index)
                             ,objFlag=false">
                    {{ index + 1 }}
                  </el-button>
                </div>

              </div>
              <!---->
              <div>
              </div>
            </el-card>
            <div class="camera_outer" style=" padding-top: 20px;  flex-shrink: 0; /* 防止左边div在容器空间不足时缩小 */   /* 使得左边div靠左，右边留出空间 */ ">
              <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay ></video>
              <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>
              <!--<div class="button"  style="height: 100px">-->
              <!--  <el-button @click="openStartScreenshot('click')" style="margin-left: 35% ;margin-top: 2%;background-color: #5999FE;color: white">截屏</el-button>-->

              <!--  &lt;!&ndash;<el-button @click="setImage()">拍照</el-button>&ndash;&gt;-->
              <!--</div>-->
            </div>

          </div>
        </el-header>
        <el-main>
          <!--TODO 客观题front-->
          <div class="objectQuestion"
               v-show=" ExamPaper.objectiveQuestions!==null&&objFlag===true&& ExamPaper.objectiveQuestions.length!==0">
            <!--<el-button type="primary" round v-for="(item,index)  in ExamPaper.objectiveQuestions" size="default"-->
            <!--           @click="tempIndex=index">题{{ index + 1 }}-->
            <!--</el-button>-->
            <div class="objQuestionContent" style="margin-top: 50px">
              <el-card class="objQuestion-card">
                <template #header>
                  <div class="card-header">
                    <h3 style=" text-align: center; margin: 0;  padding: 0;">
                      {{ ExamPaper.objectiveQuestions[tempIndex].title }}</h3>
                  </div>
                </template>
                <div>
                  <el-radio-group v-model="ExamPaper.objectiveQuestions[tempIndex].answer" @change="stagCode('obj')"   >
                    <el-radio size="large" border style="display: block"
                              v-for="(item,index) in ExamPaper.objectiveQuestions[tempIndex].options" :key="index"
                              :label="item.id"><span> {{ item.content }}</span>
                    </el-radio>
                  </el-radio-group>
                </div>
                <div
                    style="margin-top: 50px; display: flex;justify-content: center; /* 水平居中 */align-items: center; /* 垂直居中 */">
                  <el-button type="primary" round :disabled="tempIndex==0" @click="stagCode('obj'),tempIndex=tempIndex-1">
                    上一题
                  </el-button>
                  <el-button type="primary" :disabled="tempIndex+1==ExamPaper.objectiveQuestions.length"
                             @click="stagCode('obj'),tempIndex=tempIndex+1" round>下一题
                  </el-button>
                  <el-button type="primary" v-show="tempIndex+1==ExamPaper.objectiveQuestions.length"
                             @click="objFlag=false,stagCode('obj')" round>进入编程题
                  </el-button>
                </div>
              </el-card>
            </div>
          </div>
          <!--  TODO 编程题题-->
          <main role="main" class="main-container" ref="ProblemPageContainer"
                v-show=" ExamPaper.programmingQuestions!==null&&objFlag==false&&ExamPaper.programmingQuestions.length!==0">
            <div class="problem-page-head" id="problem-page-header">

              <el-row>
                <el-col :span="10">
                  <!--试题描述，提交记录-->
                  <el-tabs v-model="activeTabName" type="card" @tab-click="handleTabClick">
                    <el-tab-pane label="试题描述" name="problemDescriptionTab"></el-tab-pane>
                    <el-tab-pane label="提交记录" name="submitRecordTab"></el-tab-pane>
                  </el-tabs>
                </el-col>
                <!--语言下拉框-->
                <el-col :span="4">
<!--                  <el-select style="padding-top: 5px; padding-left: 5px"-->
<!--                             placeholder="语言"-->
<!--                             v-model="language"-->
<!--                             @change="setHighlight()"-->
<!--                  >-->
<!--                    <el-option-->
<!--                        v-for="item in languages"-->
<!--                        :key="item.id"-->
<!--                        :label="item.name"-->
<!--                        :value="item.id">-->
<!--                    </el-option>-->
<!--                  </el-select>-->
                  <input  v-bind:placeholder="examLanguageType" readonly >
                </el-col>

                <el-col :span="8">

                </el-col>

                <el-col :span="2">
                  <el-icon style="margin-top: 20px;" color="#ffc107" @click="tipDialogVisible = true">
                    <InfoFilled/>
                  </el-icon>
                </el-col>


              </el-row>
            </div>
            <!--编程训练系统使用说明-->
            <el-dialog v-model="tipDialogVisible" title="编程训练系统使用说明" width="50%" center>

              <PerfectScrollbar>
                <v-md-preview :text="INSTRUCTIONS" style="height: calc(50vh)"></v-md-preview>
              </PerfectScrollbar>

              <template #footer>
              <span class="dialog-footer">
                <el-button type="primary" @click="tipDialogVisible = false"
                >确认</el-button
                >
              </span>
              </template>
            </el-dialog>
            <!--  代码解释-->
            <div class="problem-description-code-container">
              <!---->
              <el-row>
                <el-col :span="10" class="problem-description">
                  <perfect-scrollbar class="problemDetailTab">
                    <div v-if="activeTabName == 'problemDescriptionTab'">
                      <v-md-preview :text="text" preview-class="vuepress-markdown-body"></v-md-preview>
                    </div>

                    <!--提交记录-->
                    <div v-if="activeTabName == 'submitRecordTab'" style="margin: 10px">
                      <el-skeleton :loading="submissionResultLoading" :rows="5" animated
                                   v-if="submitTrigger === true">
                        <template #default>

                          <el-card style="display: flex;justify-content: space-between">
                            <!--执行结果-->
                            <el-container>
                              <el-aside width="100">
                                <!--                                              :sub-title="currentSubmissionResult.judgeResult.judgeResultName"-->
                                <el-result
                                    icon="success"
                                    v-if="currentSubmissionResult.submissionJudgeResult === SUBMISSION_RESULT.AC.key"
                                    title="执行结果"
                                    :sub-title="result.ac"
                                >
                                </el-result>

                                <el-result
                                    icon="error"
                                    v-if="currentSubmissionResult.submissionJudgeResult === SUBMISSION_RESULT.WA.key
                                                        || currentSubmissionResult.submissionJudgeResult === SUBMISSION_RESULT.CE.key"
                                    title="执行结果"
                                    :sub-title="result.wr"
                                >
                                </el-result>
                                <el-result
                                    icon="warning"
                                    v-if="currentSubmissionResult.submissionJudgeResult !== SUBMISSION_RESULT.AC.key &&
                                                        currentSubmissionResult.submissionJudgeResult !== SUBMISSION_RESULT.WA.key &&
                                                        currentSubmissionResult.submissionJudgeResult !== SUBMISSION_RESULT.CE.key"
                                    title="执行结果"
                                    :sub-title="result.ce"
                                >

                                </el-result>
                              </el-aside>
                              <el-main>
                                <div>
                                  <br>
                                  <el-row>
                                    <span>使用语言&nbsp;:&nbsp;</span>
                                    <span style="font-weight: bold">{{ currentSubmissionResult.
                                        languageName
                                      }}</span>
                                  </el-row>
                                  <br>
                                  <el-row>
                                    <span>测评得分&nbsp;:&nbsp;</span>
                                    <span
                                        style="font-weight: bold">{{
                                        currentSubmissionResult.submissionJudgeScore
                                      }}</span>
                                  </el-row>
                                  <br>
                                  <el-row>
                                    <span>执行用时&nbsp;:&nbsp;</span>
                                    <span
                                        style="font-weight: bold">{{
                                        currentSubmissionResult.submissionUsedTime
                                      }} ms</span>
                                  </el-row>
                                  <br>
                                  <el-row>
                                    <span>内存消耗&nbsp;:&nbsp;</span>
                                    <span
                                        style="font-weight: bold">{{
                                        currentSubmissionResult.submissionUsedMemory
                                      }} kb</span>
                                  </el-row>
                                </div>

                              </el-main>
                            </el-container>

                          </el-card>


                          <el-collapse accordion style="margin-left: 5px">
                            <el-collapse-item title="显示详情">
                              <el-row>
                                <v-md-preview :text="currentSubmissionResult.submissionJudgeLog"></v-md-preview>
                              </el-row>

                            </el-collapse-item>
                            <el-collapse-item title="显示提交代码">
                              <v-md-preview :text="displayCurrentSubmissionCode"></v-md-preview>
                            </el-collapse-item>
                          </el-collapse>

                        </template>
                      </el-skeleton>

                      <table class="table table-hover">
                        <thead>
                        <tr>
                          <th>提交结果</th>
                          <th>执行用时</th>
                          <th>内存消耗</th>
                          <th>所用语言</th>
                          <th>提交时间</th>
                        </tr>
                        </thead>

                        <tbody>
                        <tr v-for="(submitResult, i) in submitRecord" v-bind:key="i"
                            @click="openSubmissionDetail(submitResult)">
                          <td v-bind:class="{'success' : submitResult.submissionJudgeResult  === SUBMISSION_RESULT.AC.key,
                                        'danger' : (submitResult.submissionJudgeResult  === SUBMISSION_RESULT.CE.key || submitResult.submissionJudgeResult  === SUBMISSION_RESULT.WA.key),
                                        'warning' : (submitResult.submissionJudgeResult  !== SUBMISSION_RESULT.CE.key && submitResult.submissionJudgeResult  !== SUBMISSION_RESULT.AC.key
                                        && submitResult.submissionJudgeResult  !== SUBMISSION_RESULT.WA.key)
                                     }"
                          >{{ submitResult.submissionJudgeResult }}
                          </td>
                          <td>{{ submitResult.submissionUsedTime}}</td>
                          <td>{{ submitResult.submissionUsedMemory}}</td>
                          <td>
                            <button
                                v-bind:class="{
                                            'badge badge-pill badge-success' : submitResult.languageName=== TRAINING_LANGUAGES.Java.value,
                                            'badge badge-pill badge-info' : submitResult.languageName === TRAINING_LANGUAGES.Python.value,
                                            'badge badge-pill badge-warning' : submitResult.languageName === TRAINING_LANGUAGES.CPlus.value
                                            || submitResult.languageName === TRAINING_LANGUAGES.C.value,
                                            }"
                            >
                              {{ submitResult.languageName }}
                            </button>
                          </td>
                          <td>{{ formatData(submitResult.submissionSubmitTime)}}</td>
                        </tr>
                        </tbody>
                      </table>

                    </div>
                  </perfect-scrollbar>
                </el-col>

                <el-col :span="14">
                  <div class="problem-code-container">
                    <div class="problem-code">
                      <codeEditor
                          :key="refresh"
                          v-model:value="code"
                          :scene="type"
                          :language-mode="languageMode"
                          ref="codeMirrorEditor"
                      ></codeEditor>
                    </div>
                  </div>
                </el-col>

              </el-row>

            </div>

            <div class="problem-description-code-footer">
              <el-row>
                <el-col :span="6">
                  <el-button style="margin-left: 16px" @click="getAllProblems(true)">
                    题目列表
                  </el-button>
                  <el-drawer
                      v-model="drawer"
                      title="题目列表"
                      :direction="direction"
                      :with-header="false"
                      :size="400"
                  >
                    <div style="display: flex; justify-content: center">
                      <perfect-scrollbar>
                        <el-table
                            :data="this.ExamPaper.programmingQuestions"
                            :height="winHeight - 56"
                            style="width: 100%"

                            @row-click="problemClick"

                        >
                          <el-table-column type="index" width="50"/>
                          <!--<el-table-column prop="problemId" label="ID" width="60"></el-table-column>-->
                          <el-table-column prop="problemName" label="试题名称" width="220"></el-table-column>
                          <el-table-column label="难度" width="80">
                            <template #default="scope">
                  <span v-bind:class="{'error' :  scope.row.problemTags === PROBLEM_TAG_SLUGS[1].value,
                                        'danger' : scope.row.problemTags === PROBLEM_TAG_SLUGS[2].value,
                                        'warning' : scope.row.problemTags === PROBLEM_TAG_SLUGS[3].value,
                                        'success' : scope.row.problemTags === PROBLEM_TAG_SLUGS[4].value,
                                     }">
                    {{ scope.row.problemTags }}
                  </span>
                            </template>

                          </el-table-column>


                        </el-table>
                      </perfect-scrollbar>
                    </div>

                  </el-drawer>


                </el-col>
                <el-col :span="2">
                  <el-button @click="viewPreviousProblem()" :disabled="this.tempProgramIndex==0">
                    上一题
                  </el-button>
                </el-col>
                <el-col :span="2">

                  <el-button @click="viewNextProblem()"
                             :disabled="this.tempProgramIndex+1==this.ExamPaper.programmingQuestions.length">
                    下一题
                  </el-button>
                </el-col>
                <el-col :span="6">

                </el-col>

                <el-col :span="4">

                </el-col>

                <el-col :span="4" style="text-align: right">
                  <el-button type="success" style="margin-right: 6px" @click="stagCode('pro')"
                             v-bind:disabled="submitDisabled === true">
                    暂存代码
                  </el-button>
                  <el-button type="success" style="margin-right: 6px" @click="submitCode()"
                             v-bind:disabled="submitDisabled === true">
                    提交代码
                  </el-button>
                  <el-button type="success" style=" margin-right: 6px" @click="submitPaper(false)"
                             v-bind:disabled="submitDisabled === true"
                  >
                    交卷
                  </el-button>
                </el-col>
              </el-row>

            </div>


            <el-dialog v-model="viewSubmissionDetail" title="提交详情" width="50%" center>

              <PerfectScrollbar>
                <v-md-preview :text="selectSubmissionResult" style="height: calc(60vh)"
                              preview-class="vuepress-markdown-body"></v-md-preview>
              </PerfectScrollbar>

              <template #footer>
              <span class="dialog-footer">
                <el-button type="primary" @click="viewSubmissionDetail = false">
                    Confirm
                </el-button>
              </span>
              </template>
            </el-dialog>


          </main>
        </el-main>
      </el-container>
    </div>
  </div>
  <!--  开始考试的对话框-->
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
// 例如：import  《组件名称》  from '《组件路径》 ';
import ExamApi from "@/api/Exam"
import CodeEditor from "./codeEditor.vue"
import CompanyApi from "@/api/company";
import API from "@/api/question";
import store from "@/store";
import html2canvas from 'html2canvas';
import {debounce} from "lodash";
import Default from "vue3-puzzle-vcode";
import {ElMessage} from "element-plus";
//TODO 数据
export default {
  // import 引入的组件需要注入到对象中才能使用
  components: {Default, CodeEditor},
  props: {},
  data() {
    // 这里存放数据
    return {
      takePhoto:false,
      cameraFlag:false,
      // 第一次考试时间
      examTime: null,
      // 持续时间
      durationTime: null,
      examEnterTime: null,  // 用户进入考试时间
      flag: true,
      // 主观题
      objFlag: true,
      token: null,
      examId: null,
      examName: null,
      examLanguageType: null,
      ExamPaper: {},
      tempIndex: 0,
      examQuesId: 0,
      //  TODO 客观题
      //  抽屉
      direction: "ltr",
      drawer: false,
      TRAINING_LANGUAGES: EXAM_LANGUAGES,
      tipDialogVisible: true,
      INSTRUCTIONS: INSTRUCTIONS,
      activeTabName: 'problemDescriptionTab',
      languages: [],
      language: null,
      languageMode: "text/x-csrc",
      tempProgramIndex: 0,
      PROBLEM_TAG_SLUGS: PROBLEM_TAG_SLUGS,
      winHeight: 1000,
      // 题目详情
      text: "",
      //  提交详情
      viewSubmissionDetail: false,
      selectSubmissionResult: {},
      code: "",
      type: 'add',
      LANGUAGE_CODE_TEMPLATE: LANGUAGE_CODE_TEMPLATE,
      refresh: true,
      //  暂存
      stagParams: {
        examId: 0,
        paperId: 0,
        list: [
          // {
          //   userId: 0,
          //   examId: 0,
          //   paperId: 0,
          //   questionId: 0,
          //   // PROGRAMMING_QUESTION
          //   questionType: "OBJECTIVE_QUESTION",
          //   content: null,
          // }
        ]
      },
      stagProGramQuestions: [],
      stagObjQuestions: [],
      stagePaper: [],
      // 提交
      currentSubmissionResult: {submissionJudgeResult:"PD"},
      submitDisabled: false,
      submitTrigger: false,
      getSubmissionResultTimer: "",
      submissionResultLoading: true,
      displayCurrentSubmissionCode: '',
      SUBMISSION_RESULT: SUBMISSION_RESULT,
      querySubmissionResultCount: 0,
      currentSubmissionId: undefined,
      submitRecord: [],
      result: {
        ac: '通过',
        wr: '错误',
        ce: '超时',
      },
      //  提交日志
      examLog: {
        examId: 0,
        examName: "string",
        paperId: 0,
        questionId: 0,
        classId: 0,
        submitTime: "string",
        startTime: "string",
        score: 0,
        content:0,
        type:null,
      },
      submissionQuestionId: null,
      examClassId: null,
      remainingHours: 0, // 剩余小时数
      remainingMinutes: 0, // 剩余分钟数
      remainingSeconds: 0 ,// 剩余秒数
      examDelayTime:0,
      screenShot:{
        userId: 0,
        url: "string",
        type: "PNG",
        examId: 0,
        name:"",
      },
      timerId:null,
      clearScreenshot:null,
      //  拍照
      videoWidth: 250,
      videoHeight: 250,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      openVideo:false,
      interval:10*60*1000,
    }

  },
  // 计算属性 类似于 data 概念
  computed: {},
  // TODO 监控 data 中的数据变化
  watch: {
    language(val) {
      this.languages.forEach(lang => {
        if (lang.id == val) {
          val = lang.name
          console.log(val,"cccccccccccccc",this.code)
        }
      })

      if (val == 'C'&&(this.code=="" ||this.code==" "||this.code==LANGUAGE_CODE_TEMPLATE[1]||this.code==LANGUAGE_CODE_TEMPLATE[2]||this.code==LANGUAGE_CODE_TEMPLATE[3])) {
        this.code = LANGUAGE_CODE_TEMPLATE[0]
        this.refreshKey()
        // this.flag=true
      }
      else if (val == 'C_PLUS_PLUS'&&(this.code==""||this.code==LANGUAGE_CODE_TEMPLATE[3]||this.code==LANGUAGE_CODE_TEMPLATE[2]||this.code==LANGUAGE_CODE_TEMPLATE[0])) {
        this.code = LANGUAGE_CODE_TEMPLATE[1]
        this.refreshKey()
      } else if (val == 'JAVA'&&(this.code==""||this.code==LANGUAGE_CODE_TEMPLATE[1]||this.code==LANGUAGE_CODE_TEMPLATE[3]||this.code==LANGUAGE_CODE_TEMPLATE[0])) {
        this.code = LANGUAGE_CODE_TEMPLATE[2]
        this.refreshKey()
      } else if (val == 'PYTHON3'&&(this.code==""||this.code==LANGUAGE_CODE_TEMPLATE[1]||this.code==LANGUAGE_CODE_TEMPLATE[2]||this.code==LANGUAGE_CODE_TEMPLATE[0])) {
        this.code = LANGUAGE_CODE_TEMPLATE[3]
        this.refreshKey()
      }
    },
    code(val) {
      console.log(val, "监控")
    }
    // this.code=val

  },
  // TODO 方法集合
  methods: {
    focusView(){
// 检查页面是否变为不可见
      if (document.visibilityState === 'hidden') {
        // 在控制台输出消息
        let parm={}
        parm.examId=localStorage.getItem("examId")
        parm.type="SKIP_PAGE"
        ExamApi.userBehavior(parm,this.token).then(res=>{
          if(res.data.success){
            ElMessage.error("鼠标离开考试页面警告一次")
          }
        })
      }
    },


    //获取时间
    getCurrentTimeFormatted() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      // 拼接成字符串
      const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedTime;
    },

    // TODO 拍照
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this;
      _this.thisCancas = document.getElementById("canvasCamera");
      _this.thisContext = this.thisCancas.getContext("2d");
      _this.thisVideo = document.getElementById("videoCamera");
      _this.thisVideo.style.display = 'block';
      // 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function(constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {//不存在则报错
            return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function(resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)"
        }
      };
      navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function(stream) {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in _this.thisVideo) {
              _this.thisVideo.srcObject = stream;
            } else {
              // 避免在新的浏览器中使用它，因为它正在被弃用。
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function(e) {
              _this.thisVideo.play();
            };
          })
          .catch(err => {
            console.log(err);
          });
    },

    //  绘制图片（拍照功能）
    setImage() {
      var _this = this;
      // canvas画图
      _this.thisContext.drawImage(
          _this.thisVideo,
          0,
          0,
          _this.videoWidth,
          _this.videoHeight
      );
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL("image/png");
      _this.imgSrc = image;//赋值并预览图片
    },
    // 关闭摄像头
    stopNavigator() {
      // this.thisVideo.srcObject.getTracks()[0].stop();
      if (this.thisVideo && this.thisVideo.srcObject) {
        const stream = this.thisVideo.srcObject;
        const tracks = stream.getTracks();

        tracks.forEach(track => track.stop());
        this.thisVideo.srcObject = null;
        this.thisVideo.style.display = 'none';
      }
    },
    // 停止摄像头流
    stopCamera() {
      if (this.currentStream) {
        this.currentStream.getTracks().forEach(track => {
          track.stop();
        });
      }
    },
    // base64转文件，此处没用到
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },


    async dataURLtoBlob(dataUrl) {
      let blob=null
      await dataUrl.then( res =>{
        // 提取Base64编码的数据部分
        let base64Data = res.split(',')[1];

        // 解码Base64数据
        let byteCharacters = atob(base64Data);
        let byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += 512) {
          let slice = byteCharacters.slice(offset, offset + 512);

          let byteNumbers = new Array(slice.length);
          for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
          }

          let byteArray = new Uint8Array(byteNumbers);
          byteArrays.push(byteArray);
        }
        // 合并所有字节数组
        blob = new Blob(byteArrays, { type: 'image/png' });
      })
      return blob;

    },

    // 截屏
    async startScreenshot() {

      const interval = 10*60*1000; // 设置截屏间隔时间，例如10秒
      this.timerId = setInterval(async () => {
        try {
          const blob=await Promise.all([
            this.dataURLtoBlob(this.takeScreenshot())
          ]);
          console.log(blob)
          if(blob!=null) {
            let _this=this
            await ExamApi.uploadImage(blob[0], _this.token).then(res => {
              if (res.data.success == true) {
                this.screenShot.examId=_this.examId;
                this.screenShot.url=res.data.content.path
                this.screenShot.name=res.data.content.name
                ExamApi.userScreenshot(_this.screenShot,_this.token).then(res=>{
                  if(res.data.success==true){
                    this.$message.success("截屏信息上传成功")
                  }
                })
                console.log(res.data)
              }
            })
          }
        } catch (error) {
          console.error('截屏或上传失败:', error);
        }
      }, interval);

    },
    // 手动截屏
    async openStartScreenshot(flag) {
      if(this.cameraFlag==false){
        this.$message.error("请先打开摄像头")
      }else {
        try {
          const blob=await Promise.all([
            this.dataURLtoBlob(this.takeScreenshot(flag))
          ]);
          console.log(blob)
          if(blob!=null) {
            let _this=this
            await ExamApi.uploadImage(blob[0], _this.token).then(res => {
              if (res.data.success == true) {
                this.screenShot.examId=_this.examId;
                this.screenShot.url=res.data.content.path
                this.screenShot.name=res.data.content.name
                ExamApi.userScreenshot(_this.screenShot,_this.token).then(res=>{

                  if(res.data.success==true) {
                    if (flag == "click") {
                      this.$message.success("截屏信息上传成功")
                    } else if (flag == "takePhoto") {
                      this.$message.success("人脸上传成功")
                      this.takePhoto = false
                    }
                  }

                })
                console.log(res.data)
              }
            })
          }
        } catch (error) {

          console.error('截屏或上传失败:', error);
        }
      }


    },
    async takeScreenshot(flag) {
      if (flag == "takePhoto") {
        const element = document.querySelector('#face-photo');
        const canvas = await html2canvas(element);
        return canvas.toDataURL('image/png');
      }
      else {
        const element = document.querySelector('#screenshot-target');
        const canvas = await html2canvas(element);
        return canvas.toDataURL('image/png');
      }

    },
    //点击客观题答题卡
    async objDTK(index) {
      this.stagCode('obj'),
          this.tempIndex = index,
          this.objFlag = true
      this.submitRecord=[]
      this.submitTrigger=false
      this.getSubmissionRecord()
    },
    async proDTK(index){
      // await this.stagCode('pro')
      // this.problemFormatToMarkdown()
      this.code = ""
      this.refreshKey()
      this.activeTabName = "problemDescriptionTab"
      this.language = null
      this.tempProgramIndex=index
      this.problemFormatToMarkdown()
      await this.getStage()
      this.stagProGramQuestions.forEach(res => {
        if (res.questionId == this.ExamPaper.programmingQuestions[this.tempProgramIndex].problemId) {
          this.code = res.content
          this.$message.success("获得暂存代码成功")
          this.refreshKey()
        }
      })
      this.submitRecord=[]
      this.submitTrigger=false
      this.getSubmissionRecord()
    },
    // 刷新代码编辑器
    refreshKey() {
      this.refresh = !this.refresh
    },
    // 交卷
    submitPaper(isTimeOut) {
      this.getStage()
      let param = {
        examId: this.examId,
        paperId: this.ExamPaper.id,
        list: this.stagePaper
      }
      param.type = "NOT_SUBMIT"
      console.log("param", param)
      param.type="MANUAL_SUBMIT"
      let haveEmpty = "";
      this.ExamPaper.objectiveQuestions.forEach(question => {
        if (question.answer == null) {
          //this.$message.error("有题目未作答，请作答")
          haveEmpty = "选择题"
        }
      })
      this.ExamPaper.programmingQuestions.forEach(question => {
        if (question.answer == null) {
          //this.$message.error("有题目未作答，请作答")
          haveEmpty = "客观题";
        }
      })
      if (!isTimeOut && haveEmpty !== "") {    // 如果未超时，用户自己提交卷子
        const confirmation = window.confirm("有" +haveEmpty+ "未作答，确认交卷吗？");
        if (confirmation) {
          this.submitExam(param);
        }
      }else { // 如果考试时间已到
        this.submitExam(param);
      }
    },

    submitExam(param) {   // 交卷
      console.log("开始交卷")
      console.log(param)
      this.getStage()
      ExamApi.userSubmitExam(param, this.token).then(res => {
        if (res.data.success == true) {
          store.commit('user/logined')
          localStorage.setItem("examFlag","end")
          this.$message.success("交卷成功")
          this.$router.push('/public');
          setTimeout(() => {
            window.location.reload(); // 刷新页面
          }, 100);
        }else {
          console.log("roo",res)
          this.$message.error(res)
        }

      }).catch(res =>{
        this.$message.error(res.response.data.message)
      })
    },
    // 提交代码
    submitCode() {
      this.$confirm('确定使用当前语言提交 ?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        // 用户点击确定后的操作
        if (_this.code.length != 0) {
          for (let i = 0; i < _this.languages.length; i++) {
            if (_this.languages[i].name === _this.examLanguageType) {
              _this.language = _this.languages[i].id
            }
          }
          if (_this.language == null) {
            _this.$message.error("未选择代码类型")
            return
          } else {
            //禁用提交
            _this.submitDisabled = true;
            //触发 el-skeleton
            _this.submitTrigger = true;
            //el-skeleton 处于 loading
            _this.submissionResultLoading = true;
            //清除查询次数
            _this.querySubmissionResultCount = 0;
            let form = {}
            let token = localStorage.getItem('token')
            form.languageId = _this.language
            form.type=_this.examLanguageType
            console.log("YyyyyyyYYY")
            console.log(_this.examLanguageType)
            form.examId=_this.examId
            form.examName=_this.examName
            form.paperId=_this.ExamPaper.id
            form.classId=_this.examClassId
            form.startTime=_this.getCurrentTimeFormatted()
            form.content=_this.code
            form.score=0
            form.code = _this.code
            form.sourceModule="exam"
            // form.problemId = _this.ExamPaper.programmingQuestions[_this.tempProgramIndex].problemId
            form.questionId = _this.ExamPaper.programmingQuestions[_this.tempProgramIndex].problemId
            console.log('form.languageId  form.type',form.languageId, form.type)
            _this.stagCode('pro')

            ExamApi.questionSubmit(form, token).then(res => {
              console.log(res.data)
              if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
                _this.$notify.warning("登录认证失败");
                _this.submitDisabled = false;
                //触发 el-skeleton
                _this.submitTrigger = false;
                //el-skeleton 处于 loading
                _this.submissionResultLoading = false;
                _this.$router.push({path: '/home'});
                return;
              }
              if (res.data.success) {
                _this.ExamPaper.programmingQuestions[_this.tempProgramIndex].answer = _this.code
                _this.activeTabName = "submitRecordTab";
                _this.$notify({
                  title: '成功',
                  message: '提交成功，正在评分，请您稍等片刻！',
                  type: 'success',
                  duration: 3000
                });

                if (res.data.data != undefined) {
                  _this.currentSubmissionId = res.data.data;
                  _this.submissionQuestionId = _this.ExamPaper.programmingQuestions[_this.tempProgramIndex].problemId
                  _this.getSubmissionResultTimer = setTimeout(_this.getSubmissionResult, 2000)
                }
                _this.submitDisabled = false;
              }
              else{
                // 设置加载状态为false
                _this.submissionResultLoading = false;
                ElMessage.error(`${res.data.message}`)
              }
            }).catch((err) => {
              _this.submitDisabled = false;
              _this.$notify({
                title: '错误',
                message: '提交失败',
                type: 'error',
                duration: 3000
              });
              console.log(err);
            }).catch(e => {
              console.log(e)
            })
          }
        } else {
          _this.$notify({
            title: '警告',
            message: '内容不能为空，请提交代码！',
            type: 'warning',
            duration: 3000
          });
        }

      }).catch(() => {
        // 用户点击取消后的操作
        console.log('操作已取消');
      });
      let _this = this;
      let langType = String(_this.languages.filter(lang=>lang.id==_this.language)[0].name)

    },
    // TODO 暂存代码
    stagCode(objFlag) {
      this.getStage()
      // location.reload();
      this.stagParams.type="MANUAL_SUBMIT"
      // this.stagParams.list=this.ExamPaper.objectiveQuestions
      this.stagParams.list=this.stagePaper
      // 客观题
      if (objFlag == 'obj') {
        this.stagParams.examId = localStorage.getItem("examId")
        this.stagParams.paperId = this.ExamPaper.id
        let info = {
          examId: this.stagParams.examId,
          paperId: this.stagParams.paperId,
          questionId: this.ExamPaper.objectiveQuestions[this.tempIndex].id,
          questionType: "OBJECTIVE_QUESTION",
          content: this.ExamPaper.objectiveQuestions[this.tempIndex].answer,
          options:[{
            answerId:null,
            optionId:this.ExamPaper.objectiveQuestions[this.tempIndex].answer,
            id:null
          }]
        }
        console.log(info,"objobj!!!!!!!!!!!!!!")
        let flag = true
        //有就更新，没有就加进去
        this.stagParams.list.forEach(stag => {
          if (stag.questionId == this.ExamPaper.objectiveQuestions[this.tempIndex].id) {
            Object.assign(stag, info);
            flag = false
          }
        })
        if (flag) {
          this.stagParams.list.unshift(info)
        }
        console.log(this.stagParams,"objobjLIST!!!!!!!!!!!!!!")
        ExamApi.userStagExam(this.stagParams, this.token).then(res => {
          if (res.data.success == true) {
            // this.$message.success("客观题暂存成功")
          }
        }).catch(res => {
          this.$message.error(res.data)
        })
      }
      // 编程题目
      else {
        this.stagParams.examId = localStorage.getItem("examId")
        this.stagParams.paperId = this.ExamPaper.id
        let info = {
          examId: this.stagParams.examId,
          paperId: this.stagParams.paperId,
          questionId: this.ExamPaper.programmingQuestions[this.tempProgramIndex].problemId,
          questionType: "PROGRAMMING_QUESTION",
          content: this.code
        }
        let flag = true
        //有就更新，没有就加进去
        this.stagParams.list.forEach(stag => {
          if (stag.questionId == this.ExamPaper.programmingQuestions[this.tempProgramIndex].problemId) {
            Object.assign(stag, info);
            flag = false
          }
        })
        if (flag) {
          this.stagParams.list.unshift(info)
        }
        ExamApi.userStagExam(this.stagParams, this.token).then(res => {
          if (res.data.success == true) {
            this.$message.success("代码暂存成功")
          }
        }).catch(res => {
          this.$message.error(res.data)
        })
      }
    },
    // TODO 获得暂存代码
    async getStage() {
      await ExamApi.userGetStagExamAnser(this.examId, this.token).then(res => {
        if (res.data.success == true) {
          this.stagePaper = res.data.data
          this.stagObjQuestions = [],
              this.stagProGramQuestions = [],
              res.data.data.forEach(question => {
                if (question.questionType == "OBJECTIVE_QUESTION") {
                  this.stagObjQuestions.push(question)
                } else {
                  this.stagProGramQuestions.push(question)
                }
              })
        }
      }).catch(res => {
        this.$message.error("出错了，请联系管理人员", res.data)
      })
    },
    //  获得用户的所有考试
    // 获得所有语言
    getAllLanguage() {
      CompanyApi.getAllLanguage(this.token).then(res => {
        if (res.data.success == true) {
          this.languages = res.data.content.filter(res=> res.id!=6&&res.id!=4)
        }
      }).catch(res => {
        this.$message.error(res)
      })
    },

    // 高亮
    setHighlight() {
      if (this.language == EXAM_LANGUAGES.C.value) {
        this.languageMode = "text/x-csrc";

      } else if (this.language == EXAM_LANGUAGES.CPlus.value) {
        this.languageMode = "text/x-c++src";

      } else if (this.language == EXAM_LANGUAGES.Java.value) {
        this.languageMode = "text/x-java";

      } else if (this.language == EXAM_LANGUAGES.Python.value) {
        this.languageMode = "text/x-python";

      }

    },
    // 问题格式
    problemFormatToMarkdown() {
      let currentProblem = this.ExamPaper.programmingQuestions[this.tempProgramIndex]
      if (currentProblem === undefined || currentProblem == "") {
        return;
      }
      this.currentProblem = eval(currentProblem);
      let limit = "::: tip <font style='color:red;'>各语言时间内存限制\n</font>"


      this.currentProblem.languageList.forEach(language => {
        limit += "<font style='color:red;'>" + language.languageName + "</font>" +
            "\t内存限制：" + language.memoryLimit + "kb\t" + "时间限制：\t" + language.timeLimit + "ms \n"
      })
      limit += " :::\n"

      let problemDescriptionString = [

        "# 题目名称" + "\n\n" + "**" + this.currentProblem.problemId + "**" + " ：" + this.currentProblem.problemName + "(" + this.currentProblem.problemCategories + ")\n\n",
        "## 题目描述" + "\n\n" + this.currentProblem.description + "\n\n",
        "## 提示" + "\n\n" + this.currentProblem.hint + "\n\n",
        "### 输入输出格式" + "\n\n",


        "::: tip <font style='color:red;'> 输入格式</font>\n" +
        this.currentProblem.inputFormat +
        "\n:::\n",

        "::: tip <font style='color:red;'>输出格式</font>\n" +
        this.currentProblem.outputFormat +
        "\n:::\n",

        limit +

        "### 输入输出样例" + "\n\n\n\n\n",


        "::: tip <font style='color:red;'>输入</font>\n" +
        this.currentProblem.sampleInput +
        "\n:::\n",

        "::: tip <font style='color:red;'>输出</font>\n" +
        this.currentProblem.sampleOutput +
        "\n:::\n",


        // "::: tip <font style='color:red;'>时间限制</font>\n" +
        // this.currentProblem.timeLimit + "ms" +
        // "\n:::\n",
        //
        // "::: tip <font style='color:red;'>内存限制</font>\n" +
        // this.currentProblem.memoryLimit + "KB" +
        // "\n:::\n",
      ];


      this.text = problemDescriptionString.join("");

    },
    //  上一个编程题
    async viewPreviousProblem() {
      // this.getSubmissionResult()
      this.code = ""
      this.language = null
      this.tempProgramIndex -= 1
      // this.getSubmissionResult()
      this.problemFormatToMarkdown()
      await this.getStage()
      this.stagProGramQuestions.forEach(res => {
        if (res.questionId == this.ExamPaper.programmingQuestions[this.tempProgramIndex].problemId) {
          this.code = res.content
          this.$message.success("获得暂存代码成功")
          this.refreshKey()
        }
      })
      this.submitRecord = []
      this.submitTrigger = false
      this.getSubmissionRecord()
      // this.refreshKey()
    },
    //  下一个编程题
    async viewNextProblem() {
      this.code = ""
      this.language = null
      this.tempProgramIndex += 1
      this.activeTabName = "problemDescriptionTab"
      this.refreshKey()
      // this.getSubmissionResult()
      this.problemFormatToMarkdown()
      await this.getStage()
      console.log(this.stagProGramQuestions, "++++++++++++++", this.ExamPaper.programmingQuestions[this.tempProgramIndex])
      this.stagProGramQuestions.forEach(res => {
        if (res.questionId == this.ExamPaper.programmingQuestions[this.tempProgramIndex].problemId) {
          this.code = res.content
          this.$message.success("获得暂存代码成功")
          this.refreshKey()
        }
      })
      this.submitRecord = []
      this.submitTrigger = false
      this.getSubmissionRecord()
    },
    //  获得所有题目
    getAllProblems() {
      this.drawer = true
    },
    //  抽屉点击题目显示
    problemClick(row, column, event) {

      this.tempProgramIndex = this.ExamPaper.programmingQuestions.findIndex(question => question.problemId == row.problemId)
      this.getSubmissionRecordNew()
      this.code = ""
      this.language = null
      this.problemFormatToMarkdown()
      this.getStage()
      this.stagProGramQuestions.forEach(res => {
        if (res.questionId == this.ExamPaper.programmingQuestions[this.tempProgramIndex].problemId) {
          this.$message.success("获得暂存代码成功")
          this.code = res.content
          this.refreshKey()
        }
      })

      this.problemFormatToMarkdown()
      this.drawer = false
    },


    //提交详情
    openSubmissionDetail(submitResult) {
      this.viewSubmissionDetail = true;

      let previewSubmissionResult = "### "

      previewSubmissionResult += (submitResult.submissionJudgeResult === SUBMISSION_RESULT.AC.key ? "✔" : "❌") + "提交结果 " + submitResult.submissionJudgeResult  + "\n"

      previewSubmissionResult += "### 执行用时 " + submitResult.executeTime + "ms\n"

      previewSubmissionResult += "### 内存消耗 " + submitResult.userMemory + "kb\n"

      previewSubmissionResult += "### 使用语言 " + submitResult.type + "\n"

      previewSubmissionResult += "### 提交时间 " + this.formatData(submitResult.submitTime) + "\n"

      previewSubmissionResult += "### 提交的代码\n"

      previewSubmissionResult +=
          "```" + "\n" +
          submitResult.content + "\n" +
          "```"
          + "\n\n"

      previewSubmissionResult += "### 评测日志\n" + submitResult.judgeLog;

      this.selectSubmissionResult = previewSubmissionResult;
    },
    //   获取检测记录
    //querySubmissionResultCount 为 第几次调用 getSubmissionResult
    async getSubmissionResult() {
      let idParam = {}
      let token = localStorage.getItem('token')
      let _this = this;
      let submissionId = _this.currentSubmissionId;  // 用于保存最新的提交id
      let latestSubmissionResult = undefined;  // 最新的提交结果
      // let loginMember = Tool.getLoginMember();
      ExamApi.getSubmissionResult(submissionId, token).then(async (res) => {

        if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
          _this.$router.push({path: '/home'});
          return;
        }
        if (res.data.success) {
          let submissionResults = res.data.data;
          _this.examQuesId = submissionResults.problemId
          console.log("winwinwinwinwinwinwinwinwinwinwinwinwinwinwinwinwinwinwinwin",submissionResults)
          if (submissionResults!== null) {
            latestSubmissionResult = submissionResults;
            //TODO 查询搭配评测结果不为PENDING
            if (latestSubmissionResult != undefined && latestSubmissionResult.submissionId === submissionId) {
              if (_this.querySubmissionResultCount++ >= 8 ||
                  (latestSubmissionResult.submissionId === submissionId
                      && latestSubmissionResult.submissionJudgeResult !== undefined
                      && latestSubmissionResult.submissionJudgeResult !==null
                      && latestSubmissionResult.submissionJudgeResult !== SUBMISSION_RESULT.PD.key)) {
                _this.submissionResultLoading = false;
                _this.currentSubmissionResult = latestSubmissionResult;

                //格式化评测日志
                console.log(_this.currentSubmissionResult,"!!!!!!!!!!!!!!!!!!!!")
                _this.currentSubmissionResult.submissionJudgeLog = _this.currentSubmissionResult.submissionJudgeLog.replace(/\n/g, "<br>");
                _this.displayCurrentSubmissionCode = "```\n" + _this.currentSubmissionResult.submissionCode + "\n```"

                _this.examLog.examId = _this.examId,
                    _this.examLog.examName = _this.examName,
                    _this.examLog.paperId = _this.ExamPaper.id,
                    _this.examLog.questionId = idParam.id,
                    _this.examLog.classId = _this.examClassId,
                    _this.examLog.submitTime = _this.getTime(latestSubmissionResult.submitTime),
                    _this.examLog.score = latestSubmissionResult.score
                _this.examLog.content= _this.code
                _this.examLog.type=latestSubmissionResult.languageName
                _this.examLog.startTime= _this.examTime
                clearTimeout(_this.getSubmissionResultTimer);
              } else {
                _this.getSubmissionResultTimer = setTimeout(_this.getSubmissionResult, 2000)
              }
            }

          }
          _this.submitRecord=[]
          _this.getSubmissionRecord()

        }else {
        }

      })
      //     .catch((err) => {
      //   console.log(err)
      // });
    },

    // 提交记录分数
    getSubmissionRecord() {
      let _this = this
      let token = localStorage.getItem('token')
      let questionId = _this.examQuesId
      ExamApi.getQSubmissionResult(questionId,_this.examId, token).then((res) => {
        if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
          _this.$router.push({path: '/home'});
          return;
        }
        if (res.data.success) {
          let submissionResults = res.data.data;
          console.log("submissionResults ", submissionResults)
          if (submissionResults.length > 0) {
            _this.submitRecord = submissionResults;
          }
        }
      }).catch((err) => {
        console.log(err)
      });
    },

    formatData(cellValue) {

      //把传过来的日期进行回炉重造一下，又创建了一个js的 Date对象，进行重新构造，转为String字符串
      //最终返回 s 就可以了
      var s = new Date(cellValue).toLocaleString();
      return s;
    },
    getTime(time=0) {
      let date=null
      if(date!=0){
        date= new Date(time);
      }else {
        date=new Date();
      }

      const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour12: false,
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        timeZone: 'Asia/Shanghai'
      };
      console.log(date.toLocaleString('zh-CN', options).replace(/\//g, '-'),"!!!!!!!!!!!!!!!!")
      return date.toLocaleString('zh-CN', options).replace(/\//g, '-');
    },


    //  倒计时
    startCountdown() {
      const examTime = new Date(this.examEnterTime)
      const durationMillis = this.durationTime  * 60 * 1000+this.examDelayTime*60*1000; // 持续时间转换为毫秒
      console.log(this.durationTime)
      const targetTime = new Date(examTime.getTime() + durationMillis); // 计算目标时间

      const updateRemainingTime = () => {
        const currentTime = new Date();
        // 获取当前时间的Date对象
        const timeDiff = targetTime.getTime() - currentTime.getTime(); // 计算目标时间和当前时间的时间差（单位：毫秒）

        if (timeDiff <= 0) {
          // 目标时间已过
          this.remainingHours = 0; // 将剩余小时数设置为0
          this.remainingMinutes = 0; // 将剩余分钟数设置为0
          this.remainingSeconds = 0; // 将剩余秒数设置为0
          this.submitPaper(true)
        } else {
          // 目标时间未过
          this.remainingHours = Math.floor(timeDiff / (1000 * 60 * 60)); // 计算剩余的小时数
          this.remainingMinutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)); // 计算剩余的分钟数
          this.remainingSeconds = Math.floor((timeDiff % (1000 * 60)) / 1000); // 计算剩余的秒数
          setTimeout(updateRemainingTime, 1000); // 每秒更新一次剩余时间
        }
      };

      updateRemainingTime();
    },
    checkFullScreen: debounce(function (){
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;
      const screenWidth = screen.width;
      const screenHeight = screen.height;

      if (windowWidth !== screenWidth || windowHeight !== screenHeight) {
        // if(!document.fullscreenElement !== null){

        const params={
          examId:this.examId,
          type:"CUT_SCREEN"
        }
        ExamApi.userBehavior(params,this.token).then(res=>{
          if(res.data.success==true){
            this.$message.error('警告一次：浏览器不是全屏状态');
          }
        })
      }
    },1000)
  },
  // 生命周期 - 创建完成（可以访问当前this 实例）
  setup() {

  },

  created() {
    this.clearScreenshot = () => {
      clearInterval(this.timerId);
    };
    this.token = localStorage.getItem('token')
    const examPaper = localStorage.getItem("examPaper")
    this.examId = localStorage.getItem("examId")
    this.ExamPaper = JSON.parse(examPaper)
    this.examTime = localStorage.getItem("examTime")
    this.examName = localStorage.getItem("examName")
    this.durationTime = localStorage.getItem("examDurationTime")
    this.examClassId = localStorage.getItem("examClassId")
    this.examEnterTime = localStorage.getItem("examEnterTime")
    this.examLanguageType = localStorage.getItem("examLanguageType")
    this.startScreenshot();


  },
  beforeUnmount() {
    this.clearScreenshot()
    this.stopNavigator();
    this.stopCamera()
    store.commit("user/logined")
    console.log("!!!!!!!!!!!!!!!!")

  },
  // TODO 挂载
  async mounted() {
    window.addEventListener('resize', this.checkFullScreen);
    this.getCompetence();
    await this.getStage()
    console.log(this.stagePaper, "测试回显!!!!!!!!!!")
    this.stagePaper.forEach(question => {
      this.ExamPaper.objectiveQuestions.forEach(obj => {
        if (question.questionId == obj.id) {
          obj.answer = question.options[0].optionId
        }
      })
      this.ExamPaper.programmingQuestions.forEach(obj => {
        if (question.questionId == obj.problemId) {
          obj.answer = question.content
        }
      })
    })
    // 添加页面激活事件监听器

    document.addEventListener('visibilitychange', this.focusView);

    // 客观
    // if (localStorage.getItem(this.examId + "examTime") == null) {
    //   const now = new Date(); // 获取当前时间的Date对象
    //   const year = now.getFullYear(); // 获取年份
    //   const month = String(now.getMonth() + 1).padStart(2, '0'); // 获取月份，并补零
    //   const day = String(now.getDate()).padStart(2, '0'); // 获取日期，并补零
    //   const hour = String(now.getHours()).padStart(2, '0'); // 获取小时，并补零
    //   const minute = String(now.getMinutes()).padStart(2, '0'); // 获取分钟，并补零
    //   const second = String(now.getSeconds()).padStart(2, '0'); // 获取秒数，并补零
    //   const formattedTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    //   this.examTime = localStorage.setItem(this.examId + "examTime", formattedTime)
    // }
    const examDelayTime=localStorage.getItem("examDelayTime")
    if (examDelayTime=='false'){
      this.examDelayTime=0

    }else {
      this.examDelayTime=Number(examDelayTime)
    }


    this.startCountdown();

    this.problemFormatToMarkdown();
    //编程
    this.getAllLanguage()
    // 获得提交记录
    this.getSubmissionRecord();
    //

  },
  // 生命周期 - 挂载完成（可以访问 DOM 元素）
  onMounted() {

  },
  onBeforeMount() {
  }, // 生命周期 - 挂载之前
  onBeforeUpdate() {
  }, // 生命周期 - 更新之前
  onUpdated() {
  }, // 生命周期 - 更新之后
  onBeforeUnmount() {
    this.clearScreenshot();
    // 移除全屏检测事件监听器
    window.removeEventListener('resize', this.checkFullScreen);
    this.stopNavigator();
    this.takePhoto=false
    // 移除事件监听器
    document.visibilityState='visible'
    document.removeEventListener('visibilitychange', this.focusView);

    // localStorage.setItem("examFlag","ed")
  }, // 生命周期 - 销毁之前
  onUnmounted() {
    this.clearScreenshot()
    this.stopNavigator();

  }, // 生命周期 - 销毁完成
  onErrorCaptured() {
    this.clearScreenshot()

  } // 如果页面有 keep-alive 缓存功能,这个函数会触发
}
</script>

<style scoped>
.red {
  color: #dd0000 !important;
}

font {
  color: red;
}

.main-container {
  height: calc(100vh - 56px);
  width: 100%;
}

.problem-page-head {
  height: 56px;
}


.problem-description-code-container {

  height: calc(100vh - 56px - 56px - 70px);
}

.problem-description {
  height: calc(100vh - 56px - 56px - 70px);
}

.problemDetailTab {
  height: calc(100vh - 56px - 56px - 70px);
}


.problem-description-code-footer {
  margin-top: 20px;
  height: 50px;

}

th {
  font-weight: normal;
}

.success {
  color: #67c23a;
}

.warning {
  color: #ffc107;
}

.danger {
  color: #EF4743;
}

.error {
  color: #ff0400;
}

@keyframes animated-border {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.4);
  }
  100% {
    box-shadow: 0 0 0 20px rgba(255, 255, 255, 0);
  }
}

.dt {
  height: 100%;
  width: 40%;
  background-color: #F7F7F7;
  /*margin-top: 15px;*/
  /*border-bottom-color: ;*/
  animation: animated-border 1.5s infinite;
  font-family: Arial;
  font-size: 18px;
  line-height: 30px;
  font-weight: bold;
  color: #409EFF;
  border: 2px solid #409EFF;
  border-radius: 10px;
  padding: 15px;
}

.questionItem {
  border: 1px;
}
</style>
